package com.itheima.auth.intergration.processor;

import com.itheima.auth.intergration.authenticator.IntegrationAuthenticator;
import com.itheima.auth.intergration.entity.IntegrationAuthenticationEntity;
import com.itheima.common.util.StringUtil;
import com.itheima.sys.client.UserClient;
import com.itheima.sys.dto.SysUserDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Component;


/**
 * 用户名/手机号   密码 方式进行认证
 */

@Component
public class UsernamePasswordAuthenticator implements IntegrationAuthenticator {


    @Autowired
    private UserClient userClient;



    /**
     * 密码认证
     * @param entity 集成认证实体
     * @return
     */
    @Override
    public SysUserDTO authenticate(IntegrationAuthenticationEntity entity) {
        //1.远程调用系统微服务获取系统用户信息
        String username = entity.getAuthParameter("username");
        String password = entity.getAuthParameter("password");
        if (username == null || password == null) {
            throw new OAuth2Exception("用户名或密码不能为空！");
        }
        //包含用户正确密码，比对密码是否正确框架比对完成
        SysUserDTO sysUserDTO = userClient.querUser(username).getData();
        if(sysUserDTO==null){
            throw new OAuth2Exception("用户名密码错误！");
        }
        return sysUserDTO;
    }

    /**
     * 密码认证方式 页面中不会提交认证类型参数
     * @param entity 集成认证实体
     * @return
     */
    @Override
    public boolean support(IntegrationAuthenticationEntity entity) {
        if(StringUtils.isEmpty(entity.getAuthType())){
            return true;
        }
        return false;
    }
}
